/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
const fs = require('fs');
const axios = require('axios');
const ProgressBar = require('progress');
const Path = require('path');
const FormData = require('form-data');

const authorization =
  'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWl4aW5fb3BlbklkIjoib3cwdEk1VWVtN18wODNOYXZQQlBIR0RBQXlUZyIsImlwIjoiMTIwLjIyNy4zNy4xMTEiLCJ1c2VySWQiOiI2YmJkOWM4Yi0yMTA4LTQzODAtOTM0My0yODk2OWQyMTU3ZmMiLCJpYXQiOjE2OTk0NTE1NjMsImV4cCI6MTcwMjA0MzU2M30.5QoR33C-xfxlobmr4fE5Q26B7pIwTnLcbv1B1xjdyjw';
// js去实现表单查询，创建模板，上传文件，生成对应记录

const categoryId = '7b87855c-ad30-4c45-bfcc-98917883b7fc';
// 调三个接口即可

// 1 遍历对应目录
let m = 0;
fs.readdir('./img/', async (err, files) => {
  if (err) {
    console.log('?????', err);
  } else {
    let str = [];
    for (let i = 0; i < files?.length; i++) {
      if (files[i] === '.DS_Store') {
        console.log(1);
      } else {
        const filePath = Path.join('./img/', files[i]);
        m++;
        const ext = Path.extname(filePath);
        const fileName = Path.basename(filePath);
        var name = fileName.replace(ext, '');
        console.log(name.length > 4 ? name.substring(0, 4) : name);
        console.log(ext);
        name = name.length > 4 ? name.substring(0, 4) : name;
        const response = await readParame(filePath, name);
        console.log('第' + m + '张', response.id);
      }
    }
  }
});

// 2 categoryId 写死 创建模板记录
async function readParame(filesPath, title) {
  const params = {
    categoryId: categoryId,
    title: title, //取文件名前4个字
  };
  var url = 'http://localhost:3009/api/template/add';
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };

  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        console.log(response.data);
        const data = await uploadTemplate(filesPath, response.data.data);
        resolve(data);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
  // await uploadTemplate(filesPath);
}

// 3 上传文件
async function uploadTemplate(filePath, data) {
  var url = 'http://localhost:3009/api/file/uploadTemplate';

  const formData = new FormData();

  formData.append('file', fs.createReadStream(filePath));
  formData.append('categoryId', categoryId);
  formData.append('templateId', data.id);
  // formData.append('templateId', "e8849fe0-d9c0-4eb7-9661-aafc6745aff6");
  formData.append('name', new Date().getTime());
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data;boundary=' + new Date().getTime(),
      authorization: authorization,
    },
  };
  const progressBar = new ProgressBar(`Uploading ${filePath} [:bar] :percent`, {
    total: fs.statSync(filePath).size,
    width: 40,
    complete: '=',
    incomplete: ' ',
  });
  const response = await axios.post(url, formData, {
    headers: config.headers,
    onUploadProgress: (progressEvent) => {
      progressBar.tick(progressEvent.loaded);
    },
  });
  console.log(`Upload complete: ${response.data.data.id}`);
  return response.data;
}
